package leetcodev1.链表;

import java.util.Deque;
import java.util.LinkedList;

public class LeetCode19 {

    //删除倒数第n个节点
    //使用快慢指针
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0) {
            return null;
        }

        ListNode dummy = new ListNode(0, head);//虚拟节点
        ListNode slow = dummy;//类似从-1开始 //代表pre
        ListNode quick = head;
        for (int i = 0; i < n; ++i) {
            quick = quick.next;//先往前走n次
        }

        while (quick != null) {
            quick = quick.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

class Answer19 {
    //1.计算链表长度
    //2.使用栈，先进后出（弹出栈的前个元素）
    //3.双指针
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);//虚拟节点
        ListNode first = head;
        ListNode second = dummy;//类似从-1开始 //代表pre
        for (int i = 0; i < n; ++i) {
            first = first.next;//先往前走n次
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        ListNode ans = dummy.next;
        return ans;
    }
}
